package org.noote.shaky_remote;

import org.noote.libs.bluetooth.SPPClient;
import org.noote.libs.shaky.comm.BluetoothCommandEvents;
import org.noote.libs.shaky.comm.BluetoothCommandProtocol;
import org.noote.libs.shaky.configuration.RobotSettings;
import org.noote.libs.shaky.configuration.RobotStates;
import org.noote.libs.virtualpad.Virtual5DPad;
import org.noote.libs.virtualpad.VirtualTouchPad;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.FrameLayout;
import android.widget.Toast;

@SuppressLint("HandlerLeak")
public class Remote_Activity extends Activity {

	static final String TAG = "Remote_Activity";
	static final String BT_ADDRESS_DEVICE = "BtAddressDevice";

	private String _sAddressDevice="";
	SPPClient _SPPClient = null;
	
	VirtualTouchPad _padTurret = null;
	Virtual5DPad _padTank = null;

	DisplayView _viewDisplay = null;
	int _iReadyStep = 0;
	
	int _iScan_Color = 3;
	int _iScan_Color_Max = 5;
	int _iScan_Correction = 1;
	
	int iFun1_Order = 0;
	
	boolean _bMultiTouch = false;
	
	RobotSettings _settings = new RobotSettings();
	RobotStates _states = new RobotStates();
	
	boolean _bInScanMode = false;
	protected static final int SCANPROGRESS_START = 0;
	protected static final int SCANPROGRESS_MSG = 1;
	protected static final int SCANPROGRESS_FINISH = 2;
	protected ProgressDialog m_mScanProgressDialog = null;
	
	protected static final int MESSAGE_UI_TOAST = 0;
	
	PowerManager.WakeLock wl = null;

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.remote);

        FrameLayout frameDisplay = (FrameLayout) findViewById(R.id.frameDisplay);
        _viewDisplay = new DisplayView(this);
		_viewDisplay._settings = _settings;
		_viewDisplay._states = _states;
		frameDisplay.addView(_viewDisplay);
		_viewDisplay.setOnTouchListener(new OnTouchListener()
		{
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				
				if(!_states._bReady) return true;
				
				_viewDisplay._padInput.touch(event, _bMultiTouch);

				if(_viewDisplay._padLoops0.haveNewEvent())
				{
					if(_viewDisplay._padLoops0.getButton())
					{
						// DO IT
					}
					_viewDisplay._padLoops0.resetNewEvent();
				}
				
				// consume motion event
		        return true;
			}
		});
		
		Bundle bundle = this.getIntent().getExtras();
		_sAddressDevice = bundle.getString(BT_ADDRESS_DEVICE);

        // Register for broadcasts when a device is disconnected !
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        this.registerReceiver(mReceiver, filter);
        
        _SPPClient = new SPPClient(mBTEvents);
	}

   private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            // When discovery finds a device
            if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
				_states._bBluetoothOnline = false;
				_viewDisplay.setTargetMessage("Disconnected...");            	
            }
        }
    };
 
	final BluetoothCommandEvents mBTEvents = new BluetoothCommandEvents()
	{
		@Override
		public void onConnected()
		{
			sendToast("Connected");
			_states._bBluetoothOnline = true;
			_viewDisplay.setTargetMessage("Online...");
			_SPPClient.sendMessage(BluetoothCommandProtocol.sendAskVersion()); // ask version
		}
		@Override
		public void onDisconnected()
		{
			sendToast("Disconnected");
        	_states._bBluetoothOnline = false;
        	_states._bReady = false;
		}
		@Override
		public void onError(String sError)
		{
			sendToast("Get Error : " + sError);
       	}
		@Override
		public void onText(String sText)
		{
			sendToast("Get text : " + sText);
		}
		@Override
		public void onVersion(String robotname, String robotversion)
		{
			_iReadyStep |= 0x01;
			
			_settings._sRobot_Name = robotname;
			_settings._sRobot_Version = robotversion;
			
			isReady();
		}
		
		private void isReady()
		{
    		if(_states._bReady == false && _iReadyStep == (0x01))
    		{
    			_states._bReady = true;
    			_viewDisplay.setTargetMessage("");
    		}
    		else if(_states._bReady == false)
    		{
    			String sWait = "Wait ";
    			sWait += ((_iReadyStep & 0x01) == 0x01)?"*":".";
    			_viewDisplay.setTargetMessage(sWait);
    		}
		}
	};

	@Override
	public void onResume()
	{
		super.onResume();
		
		if(wl == null)
		{
			PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
		    wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "Remote Robot");
		}
		if(wl != null ) wl.acquire();
		
		_viewDisplay.setTargetMessage("Try connection...");
		if(!_SPPClient.isConnected())
		{
			if(!_SPPClient.connect(_sAddressDevice))
			{
				sendToast("Cannot connect :(");    	
				_viewDisplay.setTargetMessage("Connection impossible !!!");
			}
		}
	}
	
	@Override
	public void onPause()
	{
		super.onPause();
		
		if(_SPPClient.isConnected())
		{
			// TODO close it :)
		}
		if(wl != null ) wl.release();
	}
	
	final Handler mScanProgressHandler = new Handler() {
	    @Override
		public void handleMessage(Message msg) {
	        switch (msg.what) {
	        case SCANPROGRESS_START:
	        	if(_bInScanMode)
	        		break;
	        	
	        	if(m_mScanProgressDialog != null)
	        		m_mScanProgressDialog.dismiss();
            	m_mScanProgressDialog = ProgressDialog.show(Remote_Activity.this, "Scanning", "wait...", true);

	            _bInScanMode = true;
	            break;
	        case SCANPROGRESS_MSG:
	            if (m_mScanProgressDialog!=null && m_mScanProgressDialog.isShowing()) {
	            	m_mScanProgressDialog.setMessage(((String) msg.obj));
	            }
	            break;
	        case SCANPROGRESS_FINISH:
	            if (m_mScanProgressDialog!=null && m_mScanProgressDialog.isShowing()) {
	            	m_mScanProgressDialog.dismiss();
	            	m_mScanProgressDialog = null;
	            }
	            _bInScanMode = false;
	            break;
	        }
	    }
	};

	public void sendToast(String sMsg)
	{
		_UI_Handler.sendMessage(_UI_Handler.obtainMessage(MESSAGE_UI_TOAST, sMsg));
	}
	
	final Handler _UI_Handler = new Handler() {
	    @Override
		public void handleMessage(Message msg) {
	        switch (msg.what) {
	        case MESSAGE_UI_TOAST:
	        {
	        	Toast.makeText(getApplicationContext(), (String)msg.obj, Toast.LENGTH_LONG).show();
	        }
	            break;
	        }
	    }
	};

}
